<!--
 * @Description: 
 * @Author: qingyang
 * @Date: 2022-01-11 19:05:29
 * @LastEditors: qingyang
 * @LastEditTime: 2022-12-15 20:16:07
-->
<template>
  <div class="relation-tree">
    <div class="input-box">
      <el-input
        class="input-box-content"
        placeholder="目录名称"
        v-model="frameworkName"
        @input="handleSearch"
        clearable
      >
        <template #suffix>
          <CIcon type="c-xian-sousuo"></CIcon>
        </template>
      </el-input>
    </div>
    <div class="tree-box">
      <GTree
        :isShowTag="false"
        :data="dataSource"
        :props="{
          label: 'frameworkName',
          children: 'childNodeList',
          disabled: (data:any) => {
            return data.status == 'DISABLE';
          }
        }"
        default-expand-all
        node-key="frameworkNo"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        ref="treeRef"
        :filter-node-method="filterNode"
      >
        <template #rightIcon="{ data }">
          <el-dropdown v-if="data.frameworkNo != '-1' && hasMorePermission">
            <span class="handle-button"><CIcon type="c-xian-gengduoheng"></CIcon></span>
            <template #dropdown>
              <el-dropdown-item @click="newNode(data)" v-if="!data.status && hasAddPermission"
                >新增子节点</el-dropdown-item
              >
              <el-dropdown-item
                @click="stopUsing(data)"
                v-if="!!data.status && hasUpdatePermission"
                >{{ data.status == 'DISABLE' ? '启用节点' : '停用节点' }}</el-dropdown-item
              >
            </template>
          </el-dropdown>
        </template>
      </GTree>
    </div>
  </div>
  <BaseDialog
    title="新增节点"
    append-to-body
    destroy-on-close
    :width="600"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <div class="father-node g-mb23">父节点名称：{{ parentNodeName }}</div>
    <el-form ref="formRef" :model="form" :rules="formRules" label-position="top">
      <el-form-item label="节点名称：" prop="frameworkName">
        <el-input v-model="form.frameworkName" placeholder="请输入节点名称" style="width: 100%" />
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, Ref, ref, watch, computed } from 'vue';
import { empty } from '@/utils/index';
import { useMessage } from '@/hooks/useMessage';
import { GTree } from '@/components/GTree/index';
import BaseDialog from '@/components/BaseDialog/src/BaseDialog.vue';
import {
  addEmission,
  getEmissionTree,
  updateEmissionStatus
} from '@/apis/system/config/relationship';
import {
  AddEmissionParams,
  GetEmissionListResult,
  UpdateEmissionStatusParams
} from '@/apis/system/config/model/relationshipModel';
import { store } from '@/store';
import { debounce } from 'lodash';

export default defineComponent({
  components: { GTree, BaseDialog },
  name: 'RelationshipTree',
  props: {
    title: {
      type: String,
      default: '范围目录'
    },
    desc: {
      type: String,
      default: '目录可增加子节点、停用等'
    }
  },
  emits: ['selectData'],
  setup(props, { emit }) {
    const { createConfirm, createMessage } = useMessage();

    const textMarkTag = reactive({
      tagText: '11',
      tagType: '',
      isShowTag: false
    });

    //获取树列表数据
    const dataSource = ref<GetEmissionListResult[]>([]);
    onMounted(() => {
      refreshTree();
    });

    // 新增节点弹窗状态
    const dialogVisible = ref(false);
    const hasMorePermission = computed(() => {
      let permissions = store.state.user.permissions;
      return (
        permissions.includes('ECI_RELATIONSHIP_FRAMEWORK_ADD') ||
        permissions.includes('ECI_RELATIONSHIP_FRAMEWORK_UPDATE')
      );
    });
    const hasAddPermission = computed(() => {
      let permissions = store.state.user.permissions;
      return permissions.includes('ECI_RELATIONSHIP_FRAMEWORK_ADD');
    });
    const hasUpdatePermission = computed(() => {
      let permissions = store.state.user.permissions;
      return permissions.includes('ECI_RELATIONSHIP_FRAMEWORK_UPDATE');
    });
    watch(
      () => dialogVisible.value,
      value => {
        if (!value) {
          form.frameworkName = '';
        }
      }
    );
    const treeRef: Ref = ref(null);
    const refreshTree = async (frameworkNo?: string) => {
      const data = await getEmissionTree();
      const wrapItem = {
        frameworkNo: '',
        frameworkName: '目录',
        childNodeList: data
      };
      dataSource.value = [wrapItem];

      // frameworkNo = frameworkNo || data[0].childNodeList?.[0].frameworkNo;
      frameworkNo = frameworkNo || wrapItem.frameworkNo;
      setTimeout(() => {
        treeRef.value.treeRef.setCurrentKey(frameworkNo);
        handleNodeClick(getCurrentNode(frameworkNo));
      }, 100);
    };

    const parentNodeName = ref('');
    const parentNodeNo = ref('');

    const getCurrentNode = (frameworkNo?: string) => {
      let currentNode;
      function getNode(data: any) {
        for (let i in data) {
          if (data[i].frameworkNo == frameworkNo) {
            return (currentNode = data[i]);
          }
          if (data[i].childNodeList) {
            getNode(data[i].childNodeList);
          }
        }
      }
      getNode(dataSource.value);
      return currentNode;
    };

    // 增加子节点操作
    const newNode = (data: GetEmissionListResult) => {
      parentNodeName.value = data.frameworkName;
      parentNodeNo.value = data.frameworkNo;
      dialogVisible.value = true;
    };

    // 停用节点操作
    const stopUsing = (data: GetEmissionListResult) => {
      if (data.status == 'ENABLE') {
        //目前是启用状态  点击停用
        createConfirm(
          '确认停用节点？',
          '当前节点停用后，将无法在系统中进行匹配使用，历史数据不受影响。',
          {
            iconType: 'warning',
            confirmButtonText: '停用'
          }
        ).then(async () => {
          const params: UpdateEmissionStatusParams = {
            // 排放结构目录code
            frameworkNo: data.frameworkNo,
            // 变更后的状态值 ENABLE:	启用 	DISABLE:停用
            status: 'DISABLE'
          };
          updateEmissionStatus(params).then(() => {
            createMessage.success('停用成功');
            refreshTree();
          });
        });
      } else {
        const params: UpdateEmissionStatusParams = {
          // 排放结构目录code
          frameworkNo: data.frameworkNo,
          // 变更后的状态值 ENABLE:	启用 	DISABLE:停用
          status: 'ENABLE'
        };
        updateEmissionStatus(params).then(() => {
          createMessage.success('启用成功');
          refreshTree();
        });
      }
    };

    const form = reactive<AddEmissionParams>({
      // 目录父节点编号
      parentFrameworkNo: '',
      // 新增目录节点名称
      frameworkName: ''
    });
    const formRef = ref();
    const formRules = reactive({
      frameworkName: [
        {
          required: true,
          message: '请填写节点名称',
          trigger: 'blur'
        }
      ]
    });

    // 弹窗提交操作
    const handleConfirm = () => {
      formRef.value.validate((valid: boolean) => {
        if (valid) {
          handleSubmitReq();
          dialogVisible.value = false;
        }
      });
    };
    // 添加节点接口请求
    const handleSubmitReq = () => {
      form.parentFrameworkNo = parentNodeNo.value;
      addEmission(form).then((frameworkNo: string) => {
        console.log('frameworkNo', frameworkNo);
        createMessage.success('添加成功！');
        refreshTree(frameworkNo);
      });
    };
    let currentData: any = {};
    const handleNodeClick = (data: GetEmissionListResult | undefined) => {
      console.log(data, '3333333333333333333');
      currentData = data;
      emit('selectData', data);

      // if (data?.status) {
      //   currentData = data;
      //   emit('selectData', data);
      // } else {
      //   let { frameworkNo } = currentData || {};
      //   treeRef.value.treeRef.setCurrentKey(frameworkNo);
      // }
    };
    const frameworkName = ref('');
    const filterNode = (value: string, data: GetEmissionListResult) => {
      if (!value) return true;
      return data.frameworkName.includes(value);
    };
    const handleSearch = debounce((val: string) => {
      treeRef.value.treeRef!.filter(val);
    }, 600);
    return {
      empty,
      handleNodeClick,
      dataSource,
      newNode,
      stopUsing,
      dialogVisible,
      handleConfirm,
      parentNodeName,
      formRules,
      formRef,
      form,
      treeRef,
      hasMorePermission,
      hasAddPermission,
      hasUpdatePermission,
      textMarkTag,
      filterNode,
      handleSearch,
      frameworkName
    };
  }
});
</script>
<style lang="scss" scoped>
.relation-tree {
  padding: 8px 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  .title-box {
    // height: 78px;
    padding-left: 13px;
    padding-bottom: 22px;
    p.title {
      font-size: 16px;
      font-weight: bold;
      color: #212529;
      line-height: 20px;
      padding-top: 18px;
    }
    p.desc {
      font-size: 14px;
      font-weight: 400;
      color: #a9aeb3;
      line-height: 20px;
      margin-top: 4px;
    }
  }
  .tree-box {
    flex: 1;
    overflow: auto;
  }
}
.input-box {
  width: 100%;
  overflow: hidden;
  .input-box-content {
    margin: 12px 16px;
    width: calc(100% - 32px);
  }
}
</style>
